package com.sandasai.base;

import java.lang.reflect.ParameterizedType;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@SuppressWarnings("unchecked")
public abstract class BaseDaoImpl<T> implements BaseDao<T> {

	@Resource
	private SessionFactory sessionFactory;
	private Class<T> clazz = null;
	
	public BaseDaoImpl() {
		ParameterizedType pt = (ParameterizedType)this.getClass().getGenericSuperclass();
		this.clazz = (Class<T>)pt.getActualTypeArguments()[0];
	}
	
	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	
	@Override
	public Integer save(T entity) {
		return (Integer)getSession().save(entity);
	}

	@Override
	public void delete(Integer id) {
		Object obj = findById(id);
		if(obj != null) {
			getSession().delete(obj);
		}
	}

	@Override
	public void update(T entity) {
		getSession().update(entity);
	}

	@Override
	public T findById(Integer id) {
		if(id != null) {
			return (T)getSession().get(clazz, id);
		}else {
			return null;
		}
	}

	@Override
	public List<T> findByIds(Integer[] ids) {
		if(ids.length == 0 || ids == null) {
			return Collections.emptyList();
		}else {
			return getSession().createQuery(
					"from " + clazz.getSimpleName() + " where id in (:ids)")
					.setParameterList("ids", ids).list();
		}
	}

	@Override
	public List<T> findAll() {
		return getSession().createQuery("from " + clazz.getSimpleName()).list();
	}
	@Override
	public int getAllRowCount(String hql){
		Session session = this.getSession();
		Query q = session.createQuery(hql);
		int rowCount = q.list().size();
		//session.close();
		return rowCount;
	}
	@Override
	public List<T> queryForPage(final String hql,final int offset,final int length){
		Session session = this.getSession();
		Query q = session.createQuery(hql);
		q.setFirstResult(offset);
		q.setMaxResults(length);
		List<T> list = q.list();
		//session.close();
		return list;
	}

}
